/*    
 * Copyright (c) 2013 ISoftStone, Inc.
 * All right reserved.
 *
 * 文件名：      AuthorizeServiceImpl.java
 * 作者:     Jacky Wang
 * 创建日期： 2013-7-1 下午07:51:52
 * 版本：           
 *
 */
package com.isoftstone.industry.aaa.core.service.authorization.impl;

import java.io.File;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.isoftstone.industry.persistance.bean.Bill;
import com.isoftstone.industry.persistance.bean.BillCycleConfig;
import com.isoftstone.industry.persistance.bean.BillItem;
import com.isoftstone.industry.persistance.bean.BillingCycle;
import com.isoftstone.industry.persistance.bean.EmailNotification;
import com.isoftstone.industry.persistance.bean.ProductInstance;
import com.isoftstone.industry.persistance.bean.User;
import com.isoftstone.industry.aaa.core.log.BusinessLogger;
import com.isoftstone.industry.aaa.core.log.ILogMessages;
import com.isoftstone.industry.aaa.core.service.assist.IBillCycleConfigService;
import com.isoftstone.industry.aaa.core.service.assist.IBillItemService;
import com.isoftstone.industry.aaa.core.service.assist.IBillService;
import com.isoftstone.industry.aaa.core.service.assist.IBillingCycleService;
import com.isoftstone.industry.aaa.core.service.assist.IProductInstService;
import com.isoftstone.industry.aaa.core.service.assist.IUserService;
import com.isoftstone.industry.aaa.core.service.authorization.IAuthorizeService;
import com.isoftstone.industry.aaa.core.service.email.IEmailSupportService;
import com.isoftstone.industry.aaa.utils.SystemProperties;
import com.isoftstone.modules.core.utils.DateUtils;
import com.isoftstone.modules.core.utils.lock.FileProgrameLock;
import com.isoftstone.modules.core.utils.lock.Lock;

/**
 * @author jacky
 */
@Service
public class AuthorizeServiceImpl implements IAuthorizeService
{
	@Resource
	private BusinessLogger			logger;

	@Resource
	private IUserService			userService;

	@Resource
	private IProductInstService		prodInstService;

	@Resource
	private IEmailSupportService	emailService;

	@Resource
	private IBillService			billService;

	@Resource
	private IBillingCycleService	billingCycleService;

	@Resource
	private IBillCycleConfigService	billCycleConfigService;
	@Resource
	private IBillItemService		billItemService;
	@Resource
	private SystemProperties systemProperties;

	@Override
	@Transactional
	public void timingAuthorize()
	{
		//找出欠费用户列表
		List<User> userList = userService.findOweFeeUsers();
		for (User user : userList)
		{
			Lock lock = getFileLock(user);
			//若可以成功获取文件锁
			if (lock.obtain() == true)
			{
				try{
					authorizeForUser(user);
				}catch (Exception e){
					logger.error(e.getMessage(), e);
				}finally{
					//释放文件锁
					lock.unlock();
				}
			}
		}

	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void authorizeForUser(User user)
	{
		logger.info(ILogMessages.AUTHORIZATION_OWNFEE_USER_START, user.getUsername());
		String userId = user.getId();
		List<Bill> billList = billService.findPayableBill(userId);
		BillCycleConfig billCycleConfig = billCycleConfigService.getByUser(userId);
		BillingCycle lastBillingCycle = billingCycleService.findOrCreateLastCycleByConfig(billCycleConfig);
		int interval = billCycleConfig.getStartDay()+billCycleConfig.getDurationDay()+billCycleConfig.getDueDurationDays();
		Date today = DateUtils.today();
		Date firstDay = DateUtils.getFirstDayOfMonth(today);
		Date payDeadline = DateUtils.adjustByDay(firstDay, interval-1);
		Set<String> prodInstSet = new HashSet<String>();
		for (Bill bill : billList)
		{
			BillingCycle _billingCycle = bill.getBillingCycle();
			//如果是上个周期的账单，且还没有到缴费截止日，则不用停止其服务
			if(_billingCycle.getId().equals(lastBillingCycle.getId()) && today.before(payDeadline)){
				//忽略
			}else{
				List<BillItem> billItems = billItemService.findNeedPaidItems(bill.getId());
				for (BillItem billItem : billItems)
				{
					ProductInstance prodInst = billItem.getProdInst();
					prodInstSet.add(prodInst.getId());
				}
			}
		}
		
		for (String prodInstId : prodInstSet)
		{
			prodInstService.disable(prodInstId);
		}
		
		//邮件通知用户欠费
		logger.info(ILogMessages.AUTHORIZATION_OWNFEE_USER_END, user.getUsername());
		emailService.saveEmailNotification(user.getId(), EmailNotification.Type.OWNFEE_USER_ASK_FOR_PAYMENT, null);
	}

	private Lock getFileLock(User user)
	{
		String fileName = systemProperties.getFileLockDir() + File.separator + "auhtorizing_" + user.getId() + ".lock";
		return FileProgrameLock.get(fileName);
	}
}